package com.map.core.utils;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Random;
import java.util.TimeZone;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 
 * @author DaiSy
 *
 */
public class CommonUtils {

	private static final long DAY_MINUTES = 24 * 60 * 60 * 1000;

	/**
	 * 获取当月第几天
	 * 
	 * @return
	 */
	public static int getCurrentMonthToDay() {
		Calendar cal = Calendar.getInstance();
		SimpleDateFormat sdf = new SimpleDateFormat("dd");
		return Integer.parseInt(sdf.format(cal.getTime()));
	}

	/**
	 * 产生N位非固定长度随机数(0-9999)     
	 * 
	 * @return int
	 */
	public static Integer getFourRandom(int lenght) {
		Random random = new Random();
		String fourRandom = "1";
		for (int i = 1; i <= lenght; i++)
			fourRandom = fourRandom + "0";
		fourRandom = random.nextInt(Integer.parseInt(fourRandom)) + "";
		int randLength = fourRandom.length();
		if (randLength < lenght) {
			for (int i = 1; i <= lenght - randLength; i++)
				fourRandom = "0" + fourRandom;
		}
		return Integer.parseInt(fourRandom);
	}

	/**
	 * 获取当前时间（24 yyyy-MM-dd HH:mm:ss）
	 * 
	 * @return
	 */
	public static String getCurrentTime() {
		Calendar cal = Calendar.getInstance();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		return sdf.format(cal.getTime());
	}

	/**
	 * 获取当前时间(毫秒)
	 *
	 * @return
	 */
	public static long getCurrentMillTime() {
		Calendar cal = Calendar.getInstance();
		return cal.getTimeInMillis();
	}
	/**
	 * 将时间戳按照指定格式转换为日期
	 * 
	 * @param seconds
	 * @param format
	 * @return
	 */
	public static String timeStampToDate(long seconds, String format) {
		if (format == null || format.isEmpty()) {
			format = "yyyy-MM-dd HH:mm:ss";
		}
		SimpleDateFormat sdf = new SimpleDateFormat(format);
		String date = null;
		date = sdf.format(new Date(Long.valueOf(seconds + "000")));
		return date;
	}

	public static void main(String[] arg ){
		System.out.println(MD5("123456"));
	}
	/**
	 * 字符串时间转date
	 * @param time
	 * @return
	 */
	public static Date strTimeToDate(String time){
		Date date = null;
		try {
			 DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
			 date = format.parse(time);

		 } catch (ParseException e) {
			 e.printStackTrace();
		 }
		return date;
	}
	/**
	 * 将Date按照指定格式转换为日期
	 * @param date
	 * @param format
	 * @return
	 */
	public static String dateToFormatDate(Date date, String format) {
		if (format == null || format.isEmpty()) {
			format = "yyyy-MM-dd";
		}
		SimpleDateFormat sdf = new SimpleDateFormat(format);
		return sdf.format(date);
	}

	/**
	 * 获取当前时间的时间戳
	 * 
	 * @return
	 */
	public static Date getNowTime() {
		Calendar cal = Calendar.getInstance();
		DateFormat dateFormatterChina = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM);// 格式化输出
		TimeZone timeZoneChina = TimeZone.getTimeZone("Asia/Shanghai");// 获取时区
		dateFormatterChina.setTimeZone(timeZoneChina);// 设置系统时区

		return cal.getTime();
	}

	/**
	 * 获取当前日期（yyyy-MM-dd）
	 * 
	 * @return
	 */
	public static String getCurrentDate() {
		Calendar cal = Calendar.getInstance();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		return sdf.format(cal.getTime());
	}

	/**
	 * 获取当前月份（yyyy-MM）
	 * 
	 * @return
	 */
	public static String getCurrentMonth() {
		Calendar cal = Calendar.getInstance();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
		return sdf.format(cal.getTime());
	}

	/**
	 * 获取当前月份（yyyyMM）
	 * 
	 * @return
	 */
	public static String getYearMonth() {
		Calendar cal = Calendar.getInstance();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");
		return sdf.format(cal.getTime());
	}

	/**
	 * 获取当天在月份的第几天
	 * 
	 * @return
	 */
	public static int getCurrentDay() {
		Calendar cal = Calendar.getInstance();
		int day = cal.get(Calendar.DATE);
		return day;
	}

	/**
	 * 获取当前日期前n天(yyyy-MM-dd)
	 * 
	 * @return
	 */
	public static String getBeforeDate(long day) {
		// 将字符串转为日期
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Calendar cal = Calendar.getInstance();
		long currentTimeMillis = cal.getTime().getTime();
		// 前day天
		currentTimeMillis = currentTimeMillis - day * DAY_MINUTES;
		cal.setTimeInMillis(currentTimeMillis);
		return sdf.format(cal.getTime());
	}

	/**
	 * 获取当前时间（24 HH:mm:ss）
	 * 
	 * @return
	 */
	public static String getCurrentOnlyTime() {
		Calendar cal = Calendar.getInstance();
		SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
		return sdf.format(cal.getTime());
	}

	/**
	 * 验证IP是否属于某个IP段 ipSection IP段（以'-'分隔） ip 所验证的IP号码
	 */
	public static boolean ipExistsInRange(String ip, String ipSection) {
		ipSection = ipSection.trim();
		ip = ip.trim();
		int idx = ipSection.indexOf('-');
		String beginIP = ipSection.substring(0, idx);
		String endIP = ipSection.substring(idx + 1);
		return getIp2long(beginIP) <= getIp2long(ip) && getIp2long(ip) <= getIp2long(endIP);
	}

	public static long getIp2long(String ip) {
		ip = ip.trim();
		String[] ips = ip.split("\\.");
		long ip2long = 0L;
		for (int i = 0; i < 4; ++i) {
			ip2long = ip2long << 8 | Integer.parseInt(ips[i]);
		}
		return ip2long;
	}
	public static String numberToIp(Long number) {
		String[] ip = new String[4];
		for (int i = 3; i >= 0; i--) {
			ip[i]  = String.valueOf((number & 0xff));
			number = number >> 8;
		}
		return ip[0]+"."+ip[1]+"."+ip[2]+"."+ip[3];
	}

	public static long getIp2long2(String ip) {
		ip = ip.trim();
		String[] ips = ip.split("\\.");
		long ip1 = Integer.parseInt(ips[0]);
		long ip2 = Integer.parseInt(ips[1]);
		long ip3 = Integer.parseInt(ips[2]);
		long ip4 = Integer.parseInt(ips[3]);
		long ip2long = 1L * ip1 * 256 * 256 * 256 + ip2 * 256 * 256 + ip3 * 256 + ip4;
		return ip2long;
	}

	/**
	 * match *.*.*.*
	 * 
	 * @return
	 */
	public static boolean isIpAddress(String ip) {
		String regularExpression = "^(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|[1-9])\\."
				+ "(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\." + "(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\."
				+ "(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)$";
		Pattern pattern = Pattern.compile(regularExpression);
		Matcher matcher = pattern.matcher(ip);
		return matcher.matches();
	}

	/**
	 * ip地址段是否合法
	 * 
	 * @param ipSegment
	 * @return
	 */
	public static boolean isIpAddressSegment(String ipSegment) {
		boolean ipCheck = true;
		String[] split = ipSegment.split(",");
		for (String string : split) {
			if (string.indexOf("-") != -1) {
				// 如果有“-”，再按照“-”拆分，一个个*.*.*.*的ip
				String[] split2 = string.split("-");
				if (split2.length == 2) {
					if (!isIpAddress(split2[0]) || !isIpAddress(split2[1])) {
						ipCheck = false;
					}
				} else {
					// 无效ip段
					ipCheck = false;
				}
				if (ipCheck == false) {
					return ipCheck;
				}
			} else if (string.indexOf("*") != -1) {
				// 如果有“*”，按照*号的规则匹配
				String split2 = string.replaceAll("\\*", "1");
				if (!isIpAddress(split2)) {
					ipCheck = false;
					return ipCheck;
				}
			} else {
				// 剩下的就是单个ip的
				if (!isIpAddress(string)) {
					ipCheck = false;
					return ipCheck;
				}
			}
		}
		return ipCheck;
	}

	/**
	 * 验证ip是否在id地址段中 IP地址段规则：可用逗号（,）、横杆（-）、星号（*）等分隔符，
	 * 如192.168.1.1-192.168.1.100,192.168.1.200,192.168.4.*
	 * 
	 * @param ip
	 *            操作方ip（或者代理ip）
	 * @param ipSegment
	 *            ip地址段
	 * @return
	 */
	public static boolean ipIsInIpAddressSegment(String ip, String ipSegment) {
		boolean ipCheck = false;
		if (!isIpAddress(ip)) {
			return ipCheck;
		} else {
			// 先按照逗号拆分
			String[] split = ipSegment.split(",");
			for (String string : split) {
				if (string.indexOf("-") != -1) {
					// 如果有“-”，再按照“-”拆分，一个个*.*.*.*的ip
					String[] split2 = string.split("-");
					if (split2.length == 2) {
						if (isIpAddress(split2[0]) && isIpAddress(split2[1])) {
							ipCheck = ipExistsInRange(ip, split2[0] + "-" + split2[1]);
						} else {
							// 无效ip段
							ipCheck = false;
						}
					} else {
						// 无效ip段
						ipCheck = false;
					}
					if (ipCheck == false) {
						return ipCheck;
					}
				} else if (string.indexOf("*") != -1) {
					// 如果有“*”，按照*号的规则匹配
					String[] split2 = string.split("\\*");
					int length = split2.length;
					String[] split3 = string.split("\\.");
					if (split3.length != 4 && string.lastIndexOf("*") != string.length() - 1) {
						ipCheck = false;
					} else if (length == 1) {
						ipCheck = ipExistsInRange(ip, split2[0] + "0" + "-" + split2[0] + "255");
					} else if (length == 2) {
						ipCheck = ipExistsInRange(ip, split2[0] + "0.0" + "-" + split2[0] + "255.255");
					} else if (length == 3) {
						ipCheck = ipExistsInRange(ip, split2[0] + "0.0.0" + "-" + split2[0] + "255.255.255");
					} else if (length == 4) {
						ipCheck = ipExistsInRange(ip, "0.0.0.0" + "-" + "255.255.255.255");
					} else {
						// 无效ip地址
						ipCheck = false;
					}
					if (ipCheck == false) {
						return ipCheck;
					}
				} else {
					// 剩下的就是单个ip的
					if (isIpAddress(string)) {
						ipCheck = ipExistsInRange(ip, string + "-" + string);
					} else {
						// 无效ip
						ipCheck = false;
					}
					if (ipCheck == false) {
						return ipCheck;
					}
				}
			}
		}
		return ipCheck;
	}

	/**
	 * 是否在限制时间前
	 * 
	 * @param time
	 *            (HH:mm:ss) 当前时间
	 * @param limitTime
	 *            (HH:mm:ss) 计算好的限制时间
	 * @return
	 */
	public static boolean timeLimitRepase(String time, String limitTime) {
		try {
			String times[] = time.split(":");
			String limitTimes[] = limitTime.split(":");
			if (times.length == 3 && limitTimes.length == 3) {
				int current = Integer.parseInt(times[0]) * 60 + Integer.parseInt(times[1]);
				int limit = Integer.parseInt(limitTimes[0]) * 60 + Integer.parseInt(limitTimes[1]);
				if (limit - current >= 0) {
					return true;
				}
			}
		} catch (Exception e) {
			return false;
		}
		return false;
	}

	public static int getDayBetweenTwoDays(String bday, String eday) {
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		Date sdate = null;
		Date eDate = null;
		int betweendays = 0;
		try {
			sdate = df.parse(bday);
			eDate = df.parse(eday);
			betweendays = (int) ((eDate.getTime() - sdate.getTime()) / (1000 * 60 * 60 * 24) + 0.5);// 天数间隔
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			df = new SimpleDateFormat("yyyyMM-dd");
			try {
				sdate = df.parse(bday);
				eDate = df.parse(eday);
			} catch (ParseException e1) {
				e1.printStackTrace();
			}
			betweendays = (int) ((eDate.getTime() - sdate.getTime()) / (1000 * 60 * 60 * 24) + 0.5);// 天数间隔
		}

		return betweendays + 1;
	}

	/**
	 * 获取客户端IP
	 * 
	 * @param request
	 * @return
	 */
	public static String getIpAddress(HttpServletRequest request) {
		String ipAddress = request.getHeader("x-forwarded-for");
		if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
			ipAddress = request.getHeader("Proxy-Client-IP");
		}
		if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
			ipAddress = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
			ipAddress = request.getRemoteAddr();
			if (ipAddress.equals("127.0.0.1") || ipAddress.equals("0:0:0:0:0:0:0:1")) {
				// 根据网卡取本机配置的IP
				InetAddress inet = null;
				try {
					inet = InetAddress.getLocalHost();
				} catch (UnknownHostException e) {
					e.printStackTrace();
				}
				ipAddress = inet.getHostAddress();
			}
		}
		// 对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
		if (ipAddress != null && ipAddress.length() > 15) {
			if (ipAddress.indexOf(",") > 0) {
				ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
			}
		}
		return ipAddress;

	}

	// 获取某月有多少天
	public static int getDaysByMonth(int month) {
		Calendar a = Calendar.getInstance();
		a.set(Calendar.MONTH, month - 1);
		a.set(Calendar.DATE, 1);
		a.roll(Calendar.DATE, -1);
		int maxDate = a.get(Calendar.DATE);
		return maxDate;
	}

	// 获取距本月前n月的月份
	public static String getMonthBefore(int months) {
		SimpleDateFormat sd = new SimpleDateFormat("yyyyMM");
		Calendar cal = Calendar.getInstance();
		cal.add(Calendar.MONTH, -months);
		String month = sd.format(cal.getTime());
		return month;
	}

	/**
	 * 是否存在空值
	 * 
	 * @param field
	 * @return
	 */
	public static boolean checkIsNull(Object... field) {
		for (Object str : field) {
			if (StringUtils.isBlank((String) str)) {
				return true;
			}
		}
		return false;
	}

	/**
	 * 获取MD5后的字符串
	 *
	 * @param source
	 *            进行加密的字符串
	 * @return
	 */
	public static String MD5(String source) {
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			md.update(source.getBytes());
			byte[] b = md.digest();
			StringBuffer sb = new StringBuffer();
			for (byte c : b) {
				int val = ((int) c) & 0xff;
				if (val < 16)
					sb.append("0");
				sb.append(Integer.toHexString(val));
			}
			return sb.toString().toLowerCase();
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		return null;
	}
}
